package com.xying.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author: Hisen
 * @date: 2019/9/7 0007 12:22
 * @description:
 */
public class URLImageReaderUtil {

  /**
   * 读取url图片,返回字节数组
   * @Param sonFolder
   * @return
   */
  public static byte[] getByteArray(String imageName, String sonFolder) {
    String imagePrefix = "." + PropertiesUtil.getProperty("image.suffix");
    String host = PropertiesUtil.getProperty("image.host");
    String destUrl = host + sonFolder + "/" + imageName + imagePrefix;
    byte[] data = null;

    BufferedInputStream bis = null;
    HttpURLConnection httpUrl = null;
    ByteArrayOutputStream output = null;
    URL url;
    int BUFFER_SIZE = 1024;
    byte[] buf = new byte[BUFFER_SIZE];
    int size;
    try {
      url = new URL(destUrl);
      httpUrl = (HttpURLConnection) url.openConnection();
      httpUrl.connect();
      bis = new BufferedInputStream(httpUrl.getInputStream());

      output = new ByteArrayOutputStream();
      while ((size = bis.read(buf)) != -1) {
        output.write(buf, 0, size);
      }

      data = output.toByteArray();
      output.flush();
    } catch (IOException e) {
    } catch (ClassCastException e) {
    } finally {
      try {
        bis.close();
        output.close();
        httpUrl.disconnect();
        //System.out.println(file.delete());
      } catch (IOException e) {
      } catch (NullPointerException e) {
      }
    }

    return data;
  }
}
